import {Ref} from "vue";

const buildFormUtils = (formModel: Ref<any>) => {
  const handleStringExcludeClear = (
    value: string | number | boolean,
    targetValue: string,
    targetFields: Array<string>
  ) => {
    if (value !== targetValue) {
      targetFields.forEach((item) => {
        formModel.value[item] = undefined;
      });
    }
  };
  const handleStringIncludeClear = (
    value: string | number | boolean,
    targetValue: string,
    targetFields: Array<string>
  ) => {
    if (value === targetValue) {
      targetFields.forEach((item) => {
        formModel.value[item] = undefined;
      });
    }
  };

  const handleArrayExcludeClear = (
    value: Array<string | number | boolean>,
    targetValue: string,
    targetFields: Array<string>
  ) => {
    if (!value.includes(targetValue)) {
      targetFields.forEach((item) => {
        formModel.value[item] = undefined;
      });
    }
  };
  const handleArrayIncludeClear = (
    value: Array<string | number | boolean>,
    targetValue: string,
    targetFields: Array<string>
  ) => {
    if (value.includes(targetValue)) {
      targetFields.forEach((item) => {
        formModel.value[item] = undefined;
      });
    }
  };

  /**checkbox，选中某个值，其他值清空 */
  const handleCheckboxIncludeClearOther = (
    value,
    target,
    index,
    otherField?: Array<any>
  ) => {
    const targetArrayValue = formModel.value[target];
    if (value === index) {
      if (targetArrayValue.includes(index)) {
        formModel.value[target] = [value];
        if (otherField) {
          otherField.forEach((item) => {
            formModel.value[item] = undefined;
          });
        }
      }
    } else {
      formModel.value[target] = formModel.value[target].filter((item) => {
        return item !== index;
      });
    }
  };

  // 互斥操作
  /**
   *
   * @param value  当前值
   * @param target 当前表单对象
   * @param targetValue  互斥值
   */
  function removeWithoutCopy(arr,item){
    for(let i=0;i<arr.length;i++){
      if(arr[i]===item){
        arr.splice(i,1);
        i--;
      }
    }
  }
  const handleMutuallyExclusive = (value: string | number | boolean,
                                   target: string,
                                   targetValue: Array<string | number | boolean>) => {
    console.log(value,target,targetValue)
    if (targetValue.indexOf(value) !== -1) {
      for(let i=0;i<targetValue.length;i++){
        if(targetValue[i]!==value){
          removeWithoutCopy(formModel.value[target],targetValue[i])
        }
      }
    }
  }
  return {
    handleStringExcludeClear,
    handleStringIncludeClear,
    handleArrayExcludeClear,
    handleArrayIncludeClear,
    handleCheckboxIncludeClearOther,
    handleMutuallyExclusive
  };
};
export default buildFormUtils;
